<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>录音上传</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <div class="container">
        <h1>录音并上传</h1>

        <!-- 文件上传表单 -->
        <div class="file-upload">
            <h2>上传音频文件</h2>
            <form method="POST" enctype="multipart/form-data">
                <label for="file">选择音频文件:</label>
                <input type="file" id="file" name="file_chunk" required>
                <input type="hidden" id="hidden_file_name" name="file_name" value=""> <!-- 动态设置文件名 -->
                <input type="hidden" name="is_last" value="1"> <!-- 默认网页上传为完整文件 -->
                <button type="submit">上传</button>
            </form>
        </div>

        <!-- 录音上传功能 -->
        <div class="controls">
            <h2>录音上传</h2>
            <button onclick="startRecording()">开始录音</button>
            <button onclick="stopRecording()">停止录音</button>
            <p id="status">未开始录音</p>
            <button id="uploadBtn" onclick="uploadRecording()" disabled>上传录音</button>
        </div>
    </div>

    <script>
        // 全局变量
        let recorder;
        let audioBlob;
        let isRecording = false;
        let randomString = Math.random().toString(36).substring(2, 10); // 全局随机字符串

        // 页面加载完成后设置隐藏域文件名
        document.addEventListener("DOMContentLoaded", function () {
            document.getElementById("hidden_file_name").value = randomString + "_web_uploaded_audio.wav";
        });

        // 初始化录音
        function startRecording() {
            if (isRecording) {
                return;
            }

            navigator.mediaDevices.getUserMedia({ audio: true })
                .then(stream => {
                    recorder = new MediaRecorder(stream);
                    recorder.ondataavailable = e => {
                        audioBlob = e.data;
                    };
                    recorder.onstop = () => {
                        isRecording = false;
                        document.getElementById("status").innerText = "录音已停止";
                        document.getElementById("uploadBtn").disabled = false;
                    };
                    recorder.start();
                    isRecording = true;
                    document.getElementById("status").innerText = "正在录音...";
                })
                .catch(err => {
                    console.error("录音失败: ", err);
                    alert("无法访问麦克风");
                });
        }

        // 停止录音
        function stopRecording() {
            if (!isRecording) {
                return;
            }
            recorder.stop();
        }

        // 上传录音
        function uploadRecording() {
            if (!audioBlob) {
                alert("没有录音文件可上传");
                return;
            }

            // 使用 FormData 上传录音文件
            let formData = new FormData();
            let fileName = randomString + "_web_recorded_audio.wav"; // 生成带随机字符串的文件名
            formData.append('file_chunk', audioBlob, fileName);
            formData.append('is_last', '1'); // 上传为完整文件
            formData.append('file_name', fileName); // 添加文件名到表单数据中

            fetch('/', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                // 确保响应状态是 OK (2xx)
                if (!response.ok) {
                    throw new Error('上传失败，状态码: ' + response.status);
                }
                return response.text(); // 获取响应的文本内容
            })
            .then(text => {
                console.log('上传成功:', text); // 打印返回的文本
                alert( text);
            })
            .catch(error => {
                console.error('上传失败:', error);
                alert("上传失败！");
            });
        }
    </script>
</body>
</html>
